<?php
/**
 * Created by PhpStorm.
 * User: zhao
 * Date: 2018/5/11
 * Time: 16:06
 */

namespace App\Repositories;

use App\Jobs\PushCardMessage;
use App\Models\ConcessionShare;
use App\Models\MemberOptionalField;
use App\Models\Merchant;
use App\Models\PrerogativeMcard;
use App\Models\ShareGiftRecord;
use App\Models\UserMcardRecord;
use App\Models\WxcardPrerogative;
use App\Models\WxuserMcard;
use App\Models\Mcard;

class CardRepository extends BaseRepository
{

    /**
     * 获取最低等级的卡，（默认绑定的卡）
     * @return Mcard model
     */
    public function getLowMcard()
    {
        return Mcard::where('id_merchant',session('web_merchant')->id_merchant)->orderBy('level_code','asc')->first();
    }

    public function getCardNo()
    {

        $card_no = substr(time(),0,6).str_pad(random_int(1,999999),6,0,STR_PAD_LEFT);
        $count = WxuserMcard::where('card_no',$card_no)->count();

        if($count>0) $this->getCardNo();

        return $card_no;
    }

    public function createOrShowCard($phone,$secret_param)
    {
        $low_mcard = $this->getLowMcard();

        $new_card  =  WxuserMcard::create([
            'id_mcard'=>$low_mcard->id_mcard,
            'id_merchant'=>session('web_merchant')->id_merchant,
            'id_mcard_level'=>$low_mcard->level_code,
            'remain_cash'=>0,
            'remain_credits'=>0,
            'accumulated_recharge'=>0,
            'accumulated_payments'=>0,
            'actived'=>'1',
            'created_datetime'=>now()->toDateTimeString(),
            'card_no'=>$this->getCardNo(),
            'member_optional_telephone'=>$phone
        ]);

        session(['web_wxuser_mcard'=>$new_card]);

        if(isset($record) && $record)
            $record->update(['id_register_wxuser_mcard'=>$new_card->id_wxuser_mcard]);


        if($new_card) {
            //* 请求富基接口......
            PushCardMessage::dispatch($new_card);

            //分享注册奖励
            if($secret_param)$this->_geiveShareRegisterGift($secret_param,$new_card);

            $this->createUserCard($new_card);

            if(session('web_merchant')->memberOptionalFields()->get()->count()>1)
                return ['code'=>200,'msg'=>route('bindUInfo')];

            return ['code'=>200,'msg'=>'/user-center'];
        }else{
            return ['code'=>500,'msg'=>'不好意思，請稍後再試'];
        }



    }

    //分享注册奖励
    protected function _geiveShareRegisterGift($secret_param,$new_card)
    {
        $card_no = strrev(base64_decode(strrev($secret_param)));

        $share_card = WxuserMcard::where('card_no',$card_no)->first();

        if($share_card){//如果能找到分享人，查找该商户是否设置分享用户注册奖励

            $share_register_gift = ConcessionShare::getShareRegisterGiftByMerchantId($share_card->id_merchant);

            if($share_register_gift){

                $new_card->update(['id_merchant'=>$share_card->id_merchant]);

                $this->getSeesionWxuseMcard(true);

                session('web_merchant',Merchant::find($share_card->id_merchant));

                $insert_data = [
                    'id_share_wxuser_mcard'=>$share_card->id_wxuser_mcard,
                    'id_currenct_wxuser_mcard'=>$new_card->id_wxuser_mcard,
                    'id_merchant'=>$share_card->id_merchant,
                    'id_concession_share'=>$share_register_gift->id_concession_share,
                    'old_concession_share_data'=>json_encode($share_register_gift->toArray()),
                ];
                ShareGiftRecord::create($insert_data);
            }

        }
    }

    /*public function giveShareGiftBy($secret_param)
    {
        $card_no = strrev(base64_decode(strrev($secret_param)));

        $share_card = WxuserMcard::where('card_no',$card_no)->first();

        if($share_card){//查看会员卡是否有分享有礼权限

            session(['web_merchant'=>Merchant::find($share_card->id_merchant)]);

            $wxcard_prerogative = WxcardPrerogative::where('id_prerogative',1)
                ->where('id_merchant',$share_card->id_merchant)
                ->first();

            if($wxcard_prerogative){
                $flag = false;
                if($wxcard_prerogative->for_all_member=='Y'){//如果有这个权限，看这个权限是否给所有会员
                    $flag = true;
                }else{
                    $is_power = PrerogativeMcard::where('id_wxcard_prerogative',$wxcard_prerogative->id_wxcard_prerogative)
                        ->where('id_mcard',$share_card->id_mcard)
                        ->first();
                    if($is_power) $flag = true;
                }

                if($flag){//有权限，领取奖品

                    session(['share_secret_param'=>null]);

                    return ShareGiftRecord::create([
                        'id_share_wxuser_mcard'=>$share_card->id_wxuser_mcard,
                        'id_merchant'=>$share_card->id_merchant,
                        'credits'=>$wxcard_prerogative->credits,
                        'id_tickets'=>$wxcard_prerogative->ticket,
                        'cash'=>$wxcard_prerogative->cash,
                    ]);

                }
            }

        }

        return false;
    }*/

    protected function createUserCard($new_card)
    {
        $id = $this->getSeesionUser()->primaryKey;
        $insert_data = [
            'id_wxuser_mcard'=>$new_card->id_wxuser_mcard,
            'table_type'=>$this->getSeesionUser()->table,
            'table_id'=>$this->getSeesionUser()->$id,
        ];

        UserMcardRecord::create($insert_data);
    }

    /**
     * 获取会员权益
     * @return mixed
     */
    public function getCardPrerogative()
    {
        $wxuser_mcard = $this->getSeesionWxuseMcard();

        $other_prerogative_ids = PrerogativeMcard::where('id_mcard',$wxuser_mcard->id_mcard)->get();

        //获取所有会员有效的权益
        /*return WxcardPrerogative::where('for_all_member','Y')
            ->where('id_merchant',$wxuser_mcard->id_merchant)
            ->where('is_del','N')
            ->orWhereIn('id_wxcard_prerogative',$other_prerogative_ids)
            ->where('is_del','N')
            ->get();*/
        return WxcardPrerogative::where('id_merchant',$wxuser_mcard->id_merchant)
            ->where('is_del','N')
            ->with('prerogative')
            ->get();
    }

    /**
     * 获取授权用户下的所有会员卡
     * @return mixed
     */
    public function getWxuserMcards()
    {
        $wxcard_ids = $this->getCardsByAuthUser()->pluck('id_wxuser_mcard')->toArray();

        return WxuserMcard::whereIn('id_wxuser_mcard',$wxcard_ids)->with('mcard')->get();
    }
}